const _ = require('lodash');
const nodemailer = require('nodemailer');
const dayjs = require('dayjs');
const config = require('../config');
const events = require('events');
const eventEmitter = new events.EventEmitter();
let _queue = {};

eventEmitter.on('reset', reset);

function queue(emails, contents) {
    if (!Array.isArray(emails) || !emails.length) {
        return;
    }

    for (const email of emails) {
        if (!_queue[email.address]) {
            _queue[email.address] = [];
        }
        for (const content of contents) {
            _queue[email.address].push(content);
        }
    }
}

function sendAll() {
    let keys = Object.keys(_queue);
    let i = 1;
    for (const key of keys) {
        let content = buildContent(_queue[key]);
        setTimeout(() => {
            send(key, content);
        }, i);
        i += 100;
    }
}

function send(to, content) {
    let transporter = nodemailer.createTransport({
        service: getEmailService(config.email),
        secureConnection: true, // 使用了 SSL
        auth: {
            user: config.email,
            pass: config.emailPw,
        }
    });

    let mailOptions = {
        from: `"News Monitor" <${config.email}>`,
        cc: config.email,
        to: to,
        subject: dayjs().format('YYYY/MM/DD HH:mm:ss') + '爬取结果',
        html: content
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
    });
}

function buildContent(contents) {
    let rows = contents.map(contentRowTemplate);
    let emailContent = contentTemplate(rows.join('\n'));
    return emailContent;
}

function contentRowTemplate(content) {
    return `
        <tr>
            <td style="width:50%;word-break:break-all;">${`<a href="${content.link}">${content.title}</a>`}</td>
            <td style="width:15%;text-align:center;">${dayjs(content.date).format('YYYY-MM-DD')}</td>
            <td style="width:10%;text-align:center;">${content.siteName}</td>
            <td style="width:15%;text-align:center;">${content.keywords}</td>
        </tr>
    `
}

function contentTemplate(content) {
    return `
    <table>
        <thead>
            <tr>
                <th>标题</th>
                <th>时间</th>
                <th>来源站点</th>
                <th>匹配关键字</th>
            </tr>
        </thead>
        <tbody>
            ${content}
        </tbody>
    </table>
    `
}

function reset() {
    _queue = {};
}

function listenSend() {    
    eventEmitter.on('send', sendAll);
}

function offSend() {
    eventEmitter.removeAllListeners('send');
}

function getEmailService(email) {
    email = email.toLowerCase().trim();
    if (email.endsWith('qq.com')) {
        return 'qq';
    } else if (email.endsWith('163.com')) {
        return '163'
    } else if (email.endsWith('126.com')) {
        return '126'
    }
}

module.exports = {
    queue,
    send,
    reset,
    sendAll,
    eventEmitter,
    listenSend,
    offSend
}